import { MapTile, type MapType } from '@/constants';
import { defineStore } from 'pinia';
import { reactive, ref, watchEffect } from 'vue';

export const useMapEditStore = defineStore('map-edit', () => {
  const map = reactive<MapType>([]);

  const row = ref(8);
  const col = ref(7);

  function initMap(_row?: number, _col?: number) {
    if (_row) {
      row.value = _row;
    }
    if (_col) {
      col.value = _col;
    }
    for (let index = 0; index < row.value; index++) {
      let rowItem = [];
      for (let index = 0; index < col.value; index++) {
        rowItem.push(MapTile.FLOOR);
      }
      map.push(rowItem);
    }
  }

  function updateMapRow() {
    const oldRow = map.length;
    const rowUpdate = oldRow - row.value;
    if (rowUpdate === 0) return;
    const updateValue = Math.abs(rowUpdate);
    // 减少
    if (rowUpdate > 0) {
      map.splice(oldRow - updateValue, oldRow);
    } else {
      const col = map[0]?.length;
      for (let i = 0; i < updateValue; i++) {
        map.push(new Array(col).fill(MapTile.FLOOR));
      }
    }
  }

  function updateMapCol() {
    const oldCol = map[0].length;
    const colUpdate = oldCol - col.value;
    if (colUpdate === 0) return;
    const updateValue = Math.abs(colUpdate);
    // 减少
    if (colUpdate > 0) {
      map.forEach((item) => {
        item.splice(oldCol - updateValue, oldCol);
      });
    } else {
      const addList = new Array(updateValue).fill(
        MapTile.FLOOR,
      ) as Array<MapTile>;
      map.forEach((item) => {
        item.push(...addList);
      });
    }
  }

  function setRow(_row: number) {
    row.value = _row;
  }

  function setCol(_col: number) {
    col.value = _col;
  }

  return { map, row, col, initMap, setCol, setRow, updateMapRow, updateMapCol };
});
